import axios from 'axios'
import {useUserStore} from "/@/store/modules/user";
import {Toast} from "vant";
// @ts-ignore
import Cookies from 'js-cookie'

// 是否显示重新登录
export let isRelogin = {show: false}
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const environment = import.meta.env.VITE_APP_ENV
// 创建axios实例
const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: import.meta.env.VITE_APP_EDU_API,
    // 超时
    timeout: 100000,
})

// request拦截器
service.interceptors.request.use(
    (config) => {
        const userStore = useUserStore();
        // const token = userStore.getUserToken
        if ('' != userStore.getUserToken || null == userStore.getUserToken) {
            // console.log('请求携带的token：',userStore.getUserToken)
            config.headers.token = userStore.getUserToken
            console.log('请求携带的token：', userStore.getUserToken)
        }
        config.headers['Authorization'] =
            Cookies.get('Admin-Token') || 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ4aCI6IjAzMjE0MTEzNiIsInhtIjoi5byg5LiJIiwiYmoiOiIwMzIxNDEzICAgIiwiaWQiOiIyMDIxMTE4OTMiLCJ0eXBlIjoiMSIsImV4cCI6MTcxNTUwMDY1MSwieXgiOiIwMyJ9.vriY2mFyIVBPnZ4SeHZbsbEBn8wIqj9mfzAoc8AC9Sc'
        return config;
    },
    (error) => {
        console.log(error)
        Promise.reject(error)
    },
)

// 响应拦截器
service.interceptors.response.use(
    (res) => {
        // 未设置状态码则默认成功状态
        const code = res.data.code || 200
        // 获取错误信息
        const msg = errorCode[code] || res.data.msg || errorCode['default'] || "未知错误, 请联系管理员!"
        // 二进制数据则直接返回
        if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
            return res
        }
        if (code === 401) {
            Toast.fail(msg);
            return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
        } else if (code === 500) {
            Toast.fail(msg);
            return Promise.reject(new Error(msg))
        } else if (code === 403) {
            Toast.fail(msg);
            return Promise.reject(new Error(msg))
        } else if (code === 500) {
            Toast.fail(msg);
            return Promise.reject(new Error(msg))
        } else if (code === 601) {
            Toast.fail(msg);
            return Promise.reject(new Error(msg))
        } else if (code === 302) {
            Toast.fail(msg);
            return Promise.reject(new Error(msg))
        }
        if (code === 0) {
            // 获取后端传来的 jsonStr 字符串, 如果是 jsonStr 字符串, 则解析成 json 对象
            let JsonStr = res.data.extend.json
            if (JsonStr) {
                res.data.data = JSON.parse(JsonStr);
                delete res.data.extend
            }
            console.log(`request 最终解析回的数据: `, res.data)
            return Promise.resolve(res.data)
        } else if (code !== 200) {
            Toast.fail(msg);
            return Promise.reject('error')
        } else {
            let JsonStr = res.data.extend.json
            if (JsonStr) {
                res.data.data = JSON.parse(JsonStr);
                delete res.data.extend
            }
            console.log(`request 最终解析回的数据: `, res.data)
            return Promise.resolve(res.data)
        }
    },
    (error) => {
        let {message} = error
        if (message === 'Network Error') {
            message = '后端接口连接异常'
        } else if (message.includes('timeout')) {
            message = '系统接口请求超时'
        } else if (message.includes('502')) {
            message = '系统升级中,请稍后重试!'
        } else if (message.includes('Request failed with status code')) {
            message = '系统接口' + message.substr(message.length - 3) + '异常'
        }
        Toast.fail(message);
        return Promise.reject(error)
    },
)


/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
    let result = ''
    for (const propName of Object.keys(params)) {
        const value = params[propName]
        let part = encodeURIComponent(propName) + '='
        if (value !== null && value !== '' && typeof value !== 'undefined') {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && value[key] !== '' && typeof value[key] !== 'undefined') {
                        let params = propName + '[' + key + ']'
                        let subPart = encodeURIComponent(params) + '='
                        result += subPart + encodeURIComponent(value[key]) + '&'
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + '&'
            }
        }
    }
    return result
}

const errorCode = {
    401: '认证失败，无法访问系统资源',
    403: '当前操作没有权限',
    404: '访问资源不存在',
    default: '系统未知错误，请反馈给管理员',
}


// 有解析数据的 封装


export default service
